var Collapsible = Class.create();

Object.extend(Collapsible, {
  applyCollapsible: function() {
    $$('.collapsible').each(function(el) {
      el.removeClassName('collapsible');
      el.addClassName('collapsible-processed');
      el.select('.collapsible-toggle').each(function(target) {
        Event.observe(target, "click", function() {
          Collapsible.toggle(this);
        });
      });
      
      name = el.getAttribute('collapse_name');
      if ((name) && 
          (Application.getCookie('collapse_' + name) == 1)) {
        Collapsible.toggle(el);
      }
    });
  },
  
  toggle: function(el) {
    if ($(el)) {
      if (el.hasClassName('collapsible-processed')) {
        target = el;
      }
      else {
        target = $(el).up('.collapsible-processed');
      }
      
      if (target) {
        if (target.hasClassName('expanded')) {
          target.removeClassName('expanded');
          target.addClassName('collapsed');
          collapse_value = 0;
        }
        else {
          target.removeClassName('collapsed');
          target.addClassName('expanded');
          collapse_value = 1;
        }
        
        name = target.getAttribute('collapse_name');
        if (name) {
          Application.setCookie('collapse_' + name, collapse_value);
        }
      }
    }
  }
});
